package com.ll.servlet;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;
import org.eclipse.jdt.internal.compiler.ast.ThisReference;

import net.sf.json.JSONObject;

public class ChatMessgageInbound extends MessageInbound
{
	public ChatMessgageInbound()
	{
	}
	
	@Override
	protected void onOpen(WsOutbound outbound)
	{
		super.onOpen(outbound);
		//返回当前用户列表
	}
	
	@Override
	protected void onClose(int status)
	{
		super.onClose(status);
		
		try 
		{
			WebChatServer.getInstance().releaseMessageInbound(this);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	@Override
	protected void onTextMessage(CharBuffer buffer) throws IOException
	{
		String strBuffer = buffer.toString();
		
		System.out.println("[MessageInbound] rec msg: " + strBuffer);
		
		JSONObject jo = JSONObject.fromObject(strBuffer);
		String action = (String)jo.get("action");
		
		try {
			
			//注册
			if(action.equals("regist"))
			{
				//完成注册流程
				String strRole = (String)jo.get("role");
				if(strRole.equals("service"))
				{
					String username = (String)jo.get("username");
					WebChatServer.getInstance()
						.registMessageInbound(username, this);
				}
				else if(strRole.equals("visitor"))
				{
					WebChatServer.getInstance().registMessageInbound(this);
				}
			}
			else if(action.equals("textMsg"))
			{
				//完成发送消息
				WebChatServer.getInstance().onGetMsg(jo);
			}
			else if(action.equals("reqServiceList"))
			{
				WebChatServer.getInstance().reqServiceList(this);
			}

		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
	@Override
	protected void onBinaryMessage(ByteBuffer buffer) throws IOException
	{
		
	}
	
//	private void broadcast(String msg) 
//	{
//		//Set<Integer> set = this.server.map.keySet();
//		for (Integer integer : set) 
//		{
//			WsOutbound outbound = this.server.map.get(integer);
//			CharBuffer buffer = CharBuffer.wrap(msg);
//			try 
//			{
//				outbound.writeTextMessage(buffer);
//				outbound.flush();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//	}
}